﻿
using System.Reflection;

public class Singleton<T> where T : Singleton<T>
{
    private static T _instance = null;
    private static object _lock = new object();

    protected Singleton() { }

    public static T Instance {
        get {
            lock (_lock) {
                if (null == _instance) {
                    ConstructorInfo[] ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
                    ConstructorInfo ctor = System.Array.Find(ctors, c => {
                        return 0 == c.GetParameters().Length;
                    });
                    if(null == ctor) {
                        throw new System.Exception("Non-public constructor found.");
                    }
                    _instance = ctor.Invoke(null) as T;
                }
            }
            return _instance;
        }
    }

    public static void DestroyInstance()
    {
        lock (_lock) {
            if (null != _instance) _instance = null;
        }
    }
}
